﻿#!/usr/bin/env python3

import threading
import time
import logging

num = 0

def consumer(cond):
    global num
    cond.acquire()
    while True:
        if num < 0:
            break

        logging.debug("eating, num= %d"%num)
        if num>0:
            time.sleep(1)
            num-=1
            logging.debug("eat one, remain= %d"%num)

        if num == 0:
            cond.wait()
    cond.release()
    logging.debug("over")

def producer(cond, food):
    global num
    cond.acquire()
    if num >= 0:
        logging.debug("feed {}, num={}".format(food, num))
        num += food
        cond.notify_all()
    cond.release()
    logging.debug("over")

def main():
    '''
condition, 一种thread中的同步工具.
使用 wait(),和notify()/notify_all()进行同步

'''
    global num
    logging.basicConfig(
        level = logging.DEBUG,
        format='(%(threadName)-10s) %(message)s'
    )

    cond=threading.Condition()
    p = threading.Thread(name='p', target=producer, args=(cond,10))
    c1 = threading.Thread(name='c1', target=consumer, args=(cond,))
    c2 = threading.Thread(name='c2', target=consumer, args=(cond,))

    logging.debug('start consumers')
    c1.start()
    c2.start()
    time.sleep(1.5)
    logging.debug('start producers')
    p.start()
    time.sleep(15)
    logging.debug('end all ')
    cond.acquire()
    num = -1
    cond.notify_all()
    cond.release()
    logging.debug('main over')

if __name__=='__main__':
    main()
